package com.hy.ximalaya.service;

import com.hy.common.*;
import com.hy.ximalaya.entity.Track;
import lombok.*;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.CountDownLatch;

/**
 * ximalayaCore的本地子类
 * 这个类适用于在本地部署时下载book的情况
 *
 * @author hy  2327401139@qq.com
 * @version 1.0 2021/10/15 17:06
 */
public class XimalayaLocal extends Ximalaya {

    /**
     * 存储位置
     */
    @Setter
    @Getter
    private String outputPath;

    public XimalayaLocal(String outputPath) {
        this.outputPath = PathUtils.getPath(this.outputPath, PathUtils.checkIllegalCharacter(super.getAlbum().getTitle()));
    }

    public XimalayaLocal() {
    }

    /**
     * 保存所有集到本地
     */
    public void save() throws InterruptedException {
        if (FileUtils.mkdir(this.outputPath)) {

            //因为Lambda表达式中所有的外来值都需要是final的，为了省事做个数组
            int[] i = {super.getTrackList().size() - 1};

            //计算总耗时
            long time = System.currentTimeMillis();

            CountDownLatch countDownLatch = new CountDownLatch(super.getTrackList().size());

            for (Track track : super.getTrackList()) {

                ThreadPoolUtils.Instance.executor(() -> {

                    try {
                        long sTime = System.currentTimeMillis();

                        //下载音频
                        FileUtils.writeFile(new URL(track.getPlayUrl64()), PathUtils.getPath(this.outputPath, track.getTitle() + ".mp3"));

                        long eTime = System.currentTimeMillis();
                        LogUtils.println("《", track.getTitle(), "》下载完成,用时", String.valueOf(eTime - sTime), "ms,还剩", String.valueOf(i[0]--), "集");

                    } catch (Exception e) {
                        e.printStackTrace();
                        LogUtils.println("下载 ", track.getTitle(), " 出现错误,url = ", track.getPlayUrl64());
                    } finally {
                        countDownLatch.countDown();
                    }
                });
            }

            //开始计数，锁定主线程
            countDownLatch.await();

            System.out.println("《" + super.getAlbum().getTitle() + " 》下载完成,共下载" + super.getTrackList().size() + "集,共有" + super.getTotalCount() + "集,总耗时" + (System.currentTimeMillis() - time) / 1000 + "s ✔");

        } else {
            System.out.println("创建目录出现问题....");
        }
    }

    /**
     * 保存下载链接到本地
     */
    public void saveDownloadLink() throws IOException {
        //把下载链接写出到文件
        StringBuilder sb = new StringBuilder();
        super.getTrackList().forEach((t -> sb.append(t.getPlayUrl64()).append("\n")));
        FileUtils.writeFile(sb.toString(), new File(PathUtils.getPath(this.outputPath, "下载链接.txt")));
        System.out.println("成功保存下载链接到：" + this.outputPath);
    }

}
